/* 
 * File:   StackTabWidget.cpp
 * Author: Gab'z
 * 
 * Created on 10 juin 2012, 12:44
 */

#include "StackTabWidget.h"
#include "model/Context.h"
#include <stdexcept>
namespace calculator {
    Logger* StackTabWidget::log = LoggerManager::getInstance()->getLogger("StackTabWidget");

    StackTabWidget::StackTabWidget(Stack * const stack, QWidget* parent) :
    QWidget(parent),
    Observer(),
    _stack(stack), _text(new QTextEdit(this)) {
        setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
        log->trace("CREATING TAB");
        // inscrire la tab en tant qu'observateur de la pile
        _stack->addObserver(this);
        _text->setReadOnly(true);
        updateObserver();
    }

    StackTabWidget::~StackTabWidget() {
        log->trace("DELETING TAB");
        _stack->removeObserver(this);
    }

    void StackTabWidget::reloadTabContent() {
        log->trace("reloadTabContent...");
        try {
            unsigned int visibleStackSize = Context::getInstance()->getParameters()->getVisibleStackSize();
            _text->clear();
            if (!_stack->empty()) {
                int i;
                if (_stack->size() < visibleStackSize) i = (int) _stack->size() - 1;
                else i = (int) visibleStackSize - 1;
                for (; i >= 0; i--) {
                    _text->append(QString(_stack->getConstant(i)->toString().c_str()));
                }
            }
        } catch (std::exception& e) {
            log->error(e.what());
        }
        log->trace("reloadTabContent done");
    }

    void StackTabWidget::updateObserver() {
        // on reconstitue le texte affiché dans ce widget à partir de la pile
        log->debug("updateObserver... (reconstitution de la pile affichée)");
        reloadTabContent();
        log->debug("updateObserver done");
    }

}
